# -*- coding:utf-8 -*-
# __author__ = 'GuanFengyu'

import subprocess
import xlrd
import xlwt
import os
import sys

input_filename = 'D:\WorkG\GenerateTestCasePy3\TestData\demo.xlsx'
output_filename = 'D:\WorkG\GenerateTestCasePy3\TestData\demo_res.txt'

class CreateCase:
    def __init__(self, input_filename, output_filename):
        self.input_filename = input_filename
        self.output_filename = output_filename

        self.condition_keywords = u'条件'
        self.condition_positive = [u'T',u'1']
        self.condition_negtive  = [u'F',u'0']
        self.condition_positive_text = u' 满足'
        self.condition_negtive_text  = u' 不满足'

    def read_sheet_by_col(self,workbook, sheetname):
        # 获取合并单元格的行列
        sheettext = workbook.sheet_by_name(sheetname)
        nrows = sheettext.nrows
        ncols = sheettext.ncols

        col_text = []
        for col in range(2, ncols):
            col_text.append(sheettext.col_values(col))

    def read_sheet1(self,workbook, sheetname):
        sheettext = workbook.sheet_by_name(sheetname)
        nrows = sheettext.nrows
        ncols = sheettext.ncols
        conditions = []
        results = []
        for crange in sheettext.merged_cells:
            rs, re, cs, ce = crange
            
            if sheettext.cell_value(rs, cs) == u'条件桩':
                print(u'条件桩')
                print(rs, re, cs, ce)
                for col in range(cs + 2, ncols):
                    condition = []
                    for row in range(rs, re):
                        if sheettext.cell_value(row, col) == 'T':
                            condition += sheettext.cell_value(row, 1) + ';'
                        elif sheettext.cell_value(row, col) == 'F':
                            condition += u'不满足' + sheettext.cell_value(row, 1) + ';'
                        elif sheettext.cell(row, col).ctype == 0:
                            condition += sheettext.cell_value(row, 1)
                    condition[-1] = '。'
                    conditions.append(condition)

                print(conditions)
                print('条件End')
            elif sheettext.cell_value(rs, cs) == u'动作桩':
                print(u'动作桩')
                for col in range(cs + 2, ncols):
                    for row in range(rs, re):
                        if sheettext.cell_value(row, col) == 'X':
                            results.append(sheettext.cell_value(row, 1))
                print(results)
                print('动作End')
        return [conditions, results]

    def write_excel(self,sheet, conditions, results):
        wb = xlwt.Workbook(encoding='utf-8')
        booksheet = wb.add_sheet(sheet, cell_overwrite_ok=True)
        nrows = len(conditions)
        print(nrows)
        booksheet.write(0, 0, '步骤描述')
        booksheet.write(0, 1, '预期结果')
        for i in range(0, nrows):
            booksheet.write(i + 1, 0, conditions[i])
            booksheet.write(i + 1, 1, results[i])
        wb.save(os.path.join(path, 'testcases.xls'))

    def read_excel(self):
        
        sheets = workbook.sheet_names()
        for sheet in sheets:
            conditions, results = read_sheet(workbook,sheet)
            # read_sheet_by_col(workbook,sheet)
            write_excel(sheet, conditions, results)

    def read_sheet(self, sheet):
        nrows = sheet.nrows
        ncols = sheet.ncols

        # 验证表格非空
        if nrows == 0 or ncols == 0:
            print('sheet maybe empty')
            return
        print('Sheet name:' + sheet.name)
        # 读取合并单元格，查找其中带关键字的
        condition_kw_crange = None # [起始行，结束行，起始列，结束列]
        for crange in sheet.merged_cells:
            if sheet.cell_value(crange[0],crange[2]).find(self.condition_keywords) >= 0:
                condition_kw_crange = crange 
                break
        if condition_kw_crange is None:
            print('sheet format error')
            return
        # 获得条件名称
        condition_cnt = condition_kw_crange[1] - condition_kw_crange[0]
        condition_cols = condition_kw_crange[3]
        print('Condition number:' + str(condition_cnt))
        conditions = []
        for condition_index in range(condition_kw_crange[0], condition_kw_crange[1]):
            conditions.append(sheet.cell_value(condition_index, condition_cols))
        #

        # 获得Case个数
        case_cols = condition_cols + 1
        case_cnt = ncols - case_cols
        print('Case number:' + str(case_cnt))
        # 按每个Case处理
        cases = []
        for case_index in range(case_cols, ncols):
            # 读取每个Case
            case = []
            for condition_index in range(condition_kw_crange[0], condition_kw_crange[1]):
                case_condition = conditions[condition_index - condition_kw_crange[0]]
                case_value = sheet.cell_value(condition_index, case_index)
                if case_value in self.condition_positive:
                    case_condition += self.condition_positive_text
                else:
                    case_condition += self.condition_negtive_text
                case.append(case_condition)
            # 拼接
            case_str = u'; '.join(case)
            cases.append(case_str)
            print case_str

        

        

    def process(self):
        self.workbook = xlrd.open_workbook(self.input_filename)
        self.sheet_names = self.workbook.sheet_names()

        # for sheet_name in self.sheet_names:
        #     self.read_sheet(self.workbook.sheet_by_name(sheet_name))
        self.read_sheet(self.workbook.sheet_by_name(self.sheet_names[0]))




if __name__ == '__main__':
    cc = CreateCase(input_filename, output_filename)
    cc.process()